package product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import product.domain.Brand;
import product.domain.Category;
import product.domain.CategoryBrandRelation;
import product.mapper.BrandMapper;
import product.mapper.CategoryBrandRelationMapper;
import product.mapper.CategoryMapper;
import product.service.BrandService;
import product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author panghu
 * @description 针对表【pms_category_brand_relation(品牌分类关联)】的数据库操作Service实现
 * @createDate 2023-03-04 21:03:08
 */
@Service
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationMapper, CategoryBrandRelation>
        implements CategoryBrandRelationService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private BrandService brandService;

    @Override
    public List<CategoryBrandRelation> getListByBrandId(Long brandId) {
        return baseMapper.selectListByBrandId(brandId);
    }

    @Override
    public void saveDetail(CategoryBrandRelation categoryBrandRelation) {
        Category category = categoryMapper.selectById(categoryBrandRelation.getCatelogId());
        Brand brand = brandMapper.selectById(categoryBrandRelation.getBrandId());
        categoryBrandRelation.setBrandName(brand.getName());
        categoryBrandRelation.setCatelogName(category.getName());
        this.save(categoryBrandRelation);
    }

    @Override
    public List<Brand> getBrandsByCatId(Long catId) {
        List<CategoryBrandRelation> categoryBrandRelations;
        if (catId == 0L) {
            categoryBrandRelations = this.baseMapper.selectList(null);
        } else {
            // 先找出分类品牌关系
            categoryBrandRelations = this.baseMapper.selectList(new LambdaQueryWrapper<CategoryBrandRelation>().eq(CategoryBrandRelation::getCatelogId, catId));
        }
        // 在找出品牌
        return categoryBrandRelations.stream().map(item -> brandService.getById(item.getBrandId())).collect(Collectors.toList());
    }

    @Override
    public List<Brand> getBrandsByWrapper(LambdaQueryWrapper<CategoryBrandRelation> brandWrapper) {
        List<CategoryBrandRelation> categoryBrandRelations = this.baseMapper.selectList(brandWrapper);
        Set<Long> brandId = new HashSet<>();
        categoryBrandRelations.forEach(item -> brandId.add(item.getBrandId()));
        return brandId.stream().map(item -> brandService.getById(item)).collect(Collectors.toList());
    }
}




